# -*- coding: utf-8 -*-
"""
Created on Sun Sep 21 05:30:10 2025

@author: surpass

文件操作工具函数
"""

def save_to_file(students, filename="students.txt"):
    """保存数据到文件"""
    try:
        with open(filename, "w", encoding="utf-8") as f:
            # 写入表头
            header = "学号,姓名,班级,"
            header += ",".join([f"实验{i}" for i in range(1, 9)])
            header += ","
            header += ",".join([f"作业{i}" for i in range(1, 9)])
            header += ",在线70%,在线20%,在线10%,平时总合,期末,总评\n"
            f.write(header)
            
            # 写入数据
            for student in students:
                line = f"{student.student_id},{student.name},{student.class_name},"
                line += ",".join([str(exp) for exp in student.experiments])
                line += ","
                line += ",".join([str(hw) for hw in student.homeworks])
                line += f",{student.online_learning_70},{student.online_learning_20},"
                line += f"{student.online_learning_10},{student.usual_total},"
                line += f"{student.final_exam},{student.total_score}\n"
                f.write(line)
        print(f"数据已保存到 {filename}")
        return True
    except Exception as e:
        print(f"保存文件时出错: {e}")
        return False

def load_from_file(student_manager, filename="students.txt"):
    """从文件加载数据"""
    try:
        with open(filename, "r", encoding="utf-8") as f:
            lines = f.readlines()
            # 跳过表头
            for line in lines[1:]:
                data = line.strip().split(',')
                if len(data) >= 28:  # 确保有足够的数据项
                    student_dict = {
                        'student_id': data[0],
                        'name': data[1],
                        'class': data[2],
                        'experiments': [float(x) for x in data[3:11]],
                        'homeworks': [float(x) for x in data[11:19]],
                        'online_learning_70': float(data[19]),
                        'online_learning_20': float(data[20]),
                        'online_learning_10': float(data[21]),
                        'usual_total': float(data[22]),
                        'final_exam': float(data[23]),
                        'total_score': float(data[24])
                    }
                    # 使用Student类的from_dict方法创建对象
                    from models.student import Student
                    student = Student.from_dict(student_dict)
                    student_manager.students.append(student)
        print(f"数据已从 {filename} 加载")
        return True
    except FileNotFoundError:
        print("未找到数据文件，将从空列表开始")
        return False
    except Exception as e:
        print(f"加载文件时出错: {e}")
        return False